<template>
  <el-dialog
    v-model="visible"
    title="选择关联合同"
    width="900px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="contract-selector">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.keywords"
          placeholder="请输入客户名称、合同编号或合同名称"
          clearable
          style="width: 300px; margin-right: 10px"
          @keyup.enter="searchContracts"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="searchContracts">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 合同列表 -->
      <el-table
        :data="contractList"
        border
        style="width: 100%; margin-top: 20px"
        height="400"
        @row-click="handleRowClick"
        v-loading="loading"
      >
        <el-table-column width="55" align="center">
          <template #default="scope">
            <el-radio
              :model-value="selectedContract?.id"
              :label="scope.row.id"
              @click.stop="handleRadioChange(scope.row)"
            >
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="customer" label="客户名称" width="150" show-overflow-tooltip />
        <el-table-column prop="id" label="合同ID" width="80" />
        <el-table-column prop="code" label="合同编号" width="150" show-overflow-tooltip />
        <el-table-column prop="name" label="合同名称" width="150" show-overflow-tooltip />
        <el-table-column prop="sign_time" label="签约日期" width="120">
          <template #default="scope">
            {{ new Date(parseInt(scope.row.sign_time) * 1000).toISOString().split('T')[0] }}
          </template>
        </el-table-column>
        <el-table-column prop="sign_name" label="签约人" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchForm.page"
          v-model:page-size="searchForm.limit"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmSelection" :disabled="!selectedContract">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import request from '@/utils/request'

  // 定义合同接口
  interface Contract {
    id: number
    code: string
    name: string
    customer: string
    sign_time: string
    sign_name: string
  }

  // Props
  const props = defineProps<{
    modelValue: boolean
  }>()

  // Emits
  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    select: [contract: Contract]
  }>()

  // 响应式数据
  const visible = ref(false)
  const loading = ref(false)
  const contractList = ref<Contract[]>([])
  const selectedContract = ref<Contract | null>(null)
  const total = ref(0)
  const searchForm = ref({
    keywords: '',
    page: 1,
    limit: 10,
  })

  // 监听visible变化
  watch(
    () => props.modelValue,
    newVal => {
      visible.value = newVal
      if (newVal) {
        loadContracts()
      }
    }
  )

  watch(visible, newVal => {
    emit('update:modelValue', newVal)
  })

  // 加载合同列表
  const loadContracts = async () => {
    loading.value = true
    try {
      const response: any = await request({
        url: '/api/contract/contract/list',
        method: 'get',
        params: {
          page: searchForm.value.page,
          limit: searchForm.value.limit,
          keywords: searchForm.value.keywords,
          cate_id: 5, // 只查询cate_id=5的合同
        },
      })

      if (response.code === 0) {
        contractList.value = response.data.list || []
        total.value = response.data.count || 0
      } else {
        ElMessage.error(response.msg || '获取合同列表失败')
      }
    } catch (error) {
      console.error('获取合同列表失败:', error)
      ElMessage.error('获取合同列表失败')
    } finally {
      loading.value = false
    }
  }

  // 搜索合同
  const searchContracts = () => {
    searchForm.value.page = 1
    loadContracts()
  }

  // 重置搜索
  const resetSearch = () => {
    searchForm.value.keywords = ''
    searchForm.value.page = 1
    loadContracts()
  }

  // 处理分页大小改变
  const handleSizeChange = (val: number) => {
    searchForm.value.limit = val
    loadContracts()
  }

  // 处理当前页改变
  const handleCurrentChange = (val: number) => {
    searchForm.value.page = val
    loadContracts()
  }

  // 处理行点击
  const handleRowClick = (row: Contract) => {
    selectedContract.value = row
  }

  // 处理单选框变化
  const handleRadioChange = (contract: Contract) => {
    selectedContract.value = contract
  }

  // 确认选择
  const confirmSelection = () => {
    if (selectedContract.value) {
      emit('select', selectedContract.value)
      handleClose()
    }
  }

  // 关闭对话框
  const handleClose = () => {
    visible.value = false
    selectedContract.value = null
    searchForm.value = {
      keywords: '',
      page: 1,
      limit: 10,
    }
  }
</script>

<style scoped>
  .contract-selector {
    padding: 0 20px;
  }

  .search-bar {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
